package net.zhengxinyun.performance.service.workSupervision;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.dto.ExcelDTO;
import net.zhengxinyun.performance.entity.DepartmentEntity;
import net.zhengxinyun.performance.entity.WorkSupervisionEntity;
import net.zhengxinyun.performance.filter.WorkSupervisionFilter;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.workSupervision.WorkScoreEntityMapper;
import net.zhengxinyun.performance.mapper.workSupervision.WorkSupervisionEntityMapper;
import net.zhengxinyun.performance.service.exportService.ExcelDtoService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by hyp1202 on 2018/12/12.
 */
@Service
public class WorkSupervisionServiceImpl implements WorkSupervisionService {

    private WorkSupervisionEntityMapper workSupervisionEntityMapper;
    private WorkScoreEntityMapper workScoreEntityMapper;


    @Autowired
    private DepartmentEntityMapper departmaper;

    @Autowired
    private ExcelDtoService excelDtoService;
    @Autowired
    public WorkSupervisionServiceImpl(WorkSupervisionEntityMapper workSupervisionEntityMapper, WorkScoreEntityMapper workScoreEntityMapper) {
        this.workSupervisionEntityMapper = workSupervisionEntityMapper;
        this.workScoreEntityMapper = workScoreEntityMapper;
    }

    @Override
    public String insert(WorkSupervisionEntity workSupervisionEntity) {
        int i = workSupervisionEntityMapper.insert(workSupervisionEntity);
        if (i == 0){
            return "添加失败,请联系管理员";
        }
        return "添加成功";
    }

    @Override
    @Transactional
    public String delete(WorkSupervisionEntity workSupervisionEntity) {
      /*  int a = workScoreEntityMapper.deleteByIndicators(workSupervisionEntity.getId());
        if (a == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "指标下的分数删除失败，请重试";
        }*/
        int i = workSupervisionEntityMapper.deleteByPrimaryKey(workSupervisionEntity.getId());
        if (i == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "删除失败，请重试";
        }
        return "删除成功";
    }

    @Override
    public String update(WorkSupervisionEntity workSupervisionEntity) {
      /*  List<String> units = workSupervisionEntity.getCooperateUnits();
        workSupervisionEntity.setCooperateUnit(String.join(",",units));
*/
        int i = workSupervisionEntityMapper.updateByPrimaryKeySelective(workSupervisionEntity);
        if (i == 0){
            return "修改失败，请联系管理员";
        }
        return "修改成功";
    }

    @Override
    public List<WorkSupervisionFilter> query(WorkSupervisionFilter filter) {
        List<WorkSupervisionFilter> list = workSupervisionEntityMapper.query(filter);
       /* for (WorkSupervisionFilter workSupervisionFilter:list) {
            if (StringUtils.isNotBlank(workSupervisionFilter.getPoint())){
                workSupervisionFilter.setScore(Double.valueOf(workSupervisionFilter.getPoint()));
            }else {
                continue;
            }
        }*/
        return list;
    }

    @Override
    public Integer queryForCount(WorkSupervisionFilter filter) {
        return workSupervisionEntityMapper.queryForCount(filter);
    }



    @Override
    @Transactional
    public String setPoint(WorkSupervisionEntity workSupervisionEntity) {
        workSupervisionEntity.setAudit("0");
        int i = workSupervisionEntityMapper.updateByPrimaryKeySelective(workSupervisionEntity);
        if (i == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "设置分数失败，请重试";
        }
        return "设置分数成功";
    }
    // 导入数据
    @Override
    @Transactional
    public String importData(MultipartFile file) {
        if (file.getOriginalFilename().endsWith(".xls") == false && file.getOriginalFilename().endsWith(".xlsx") == false) {
            return "文件后缀不对";
        }
        String filePath;
        return  null;
    }

    // 导入指标
    @Override
    public HashMap<String,Object> importPoint(MultipartFile file) {
        HashMap<String,Object> map = new HashMap<>();
        String batchNum = DateUtils.getCurrentDateTimeNum();//批次号
        InputStream inp =null;

        try {
            inp= file.getInputStream();
            Workbook wb = WorkbookFactory.create(inp);
            Sheet sheet = wb.getSheetAt(0);
            if(sheet==null)
            {
                map.put("code",500);
                map.put("message","表格数据为空");
                return map;

            }
            // 校验表头；


            List<ExcelDTO> dtolists = new ArrayList<>();
            //处理数据 存到 inv_data临时表
            int lastRow  = sheet.getPhysicalNumberOfRows();
            for (int i = 1; i < lastRow; i++) {
                Row row = sheet.getRow(i);
                ExcelDTO dto = new ExcelDTO();
                dto.setAvail(1);
                String remark="",head="";

                Cell cell0 = row.getCell(0); //序号
                if(cell0==null)
                {
                    cell0 = row.createCell(0);
                }
                cell0.setCellType(Cell.CELL_TYPE_STRING);
                head =  cell0.getStringCellValue();
                dto.setCell0(head);

                Cell cell1 = row.getCell(1); //年份
                if(cell1==null)
                {
                    cell1 = row.createCell(1);
                    remark ="年份不能为空;"+remark;
                }
                cell1.setCellType(Cell.CELL_TYPE_STRING);
                head =  cell1.getStringCellValue();
                dto.setCell1(head);


                Cell cell2 = row.getCell(2); //指标名称
                if(cell2==null)
                {
                    cell2 = row.createCell(2);
                    remark ="指标名称不能为空;"+remark;
                }
                cell2.setCellType(Cell.CELL_TYPE_STRING);
                head =  cell2.getStringCellValue();
                dto.setCell2(head);

                Cell cell3 = row.getCell(3); //扣分上限
                if(cell3==null)
                {
                    cell3 = row.createCell(4);
                    remark ="扣分上限不能为空;"+remark;
                }
                cell3.setCellType(Cell.CELL_TYPE_STRING);
                head =  cell3.getStringCellValue();
                dto.setCell3(head);

                Cell cell4 = row.getCell(4); //市考核责任单位
                if(cell4==null)
                {
                    cell4 = row.createCell(4);
                    remark ="市考核责任单位;"+remark;
                }
                cell4.setCellType(Cell.CELL_TYPE_STRING);
                head =  cell4.getStringCellValue();
                dto.setCell4(head);

                Cell cell5 = row.getCell(5); //工作目标牵头单位
                if(cell5==null)
                {
                    cell5 = row.createCell(5);
                    remark ="工作目标牵头单位不能为空;"+remark;
                    dto.setAvail(0);
                }
                cell5.setCellType(Cell.CELL_TYPE_STRING);
                head =  cell5.getStringCellValue();
                dto.setCell5(head);

                List<DepartmentEntity> departs =null;

                if(StringUtils.isNotBlank(head))
                {
                    departs = departmaper.getDepartByNameList(head);
                    if(ObjectUtils.isBlank(departs))
                    {
                        remark ="未根据关键字【"+head+"】匹配到牵头单位;"+remark;
                        dto.setAvail(0);
                        dto.setCell23(null);
                    }else {
                        if(departs.size()>1)
                        {
                            remark ="匹配到多个相同的牵头单位，单位可能存在重复，请联系管理员;"+remark;
                            dto.setAvail(0);
                            dto.setCell23(null);
                        }else {
                            dto.setCell23(departs.get(0).getDepartcode());
                            //dto.setName23(name.get(0).getDepartment());
                            remark = "根据关键字【" + head + "】匹配到牵头单位【" + departs.get(0).getDepartment() + "】";
                        }
                    }
                }




                Cell cell6 = row.getCell(6); //考核配合单位
                if(cell6==null)
                {
                    cell6 = row.createCell(6);
                  //  remark ="指标名称不能为空;"+remark;
                }
                cell6.setCellType(Cell.CELL_TYPE_STRING);
                head =  cell6.getStringCellValue();
                dto.setCell6(head);

                dto.setBatchNum(batchNum);
                dto.setRemark(remark);
                dtolists.add(dto);

            }

            //保存临时表
            int i = excelDtoService.saveData(dtolists);
            if(i==0)
            {
                map.put("code",500);
                map.put("message","导入失败");
                return map;
            }



        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }

        map.put("code",200);
        map.put("message","上传校验成功");
        map.put("batchNum",batchNum);
        return  map;
    }


    //确认保存
    @Override
    public int batchSaveWorkIndexs(List<ExcelDTO> list) {

        List<WorkSupervisionEntity> wordlist  = new ArrayList<>();
        for (ExcelDTO dto : list) {
            WorkSupervisionEntity entity = new WorkSupervisionEntity();
            entity.setSort(Integer.parseInt(dto.getCell0()));
            entity.setDateTime(dto.getCell1());
            entity.setIndexName(dto.getCell2());
            entity.setMaxPoint(Double.parseDouble(dto.getCell3()));
            entity.setCityResponUnit(dto.getCell4());
            entity.setLeadUnit(dto.getCell5());
            entity.setCooperateUnit(dto.getCell6());
            entity.setDepartCode(dto.getCell23());
            wordlist.add(entity);
        }
       int i = workSupervisionEntityMapper.batchInsert(wordlist);


        return i;
    }
}
